from datetime import datetime
from app import db
import json


class MateCriteria(db.Model):
    """择偶条件表 - 重构版支持多选条件"""
    __tablename__ = 'mate_criteria'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    
    # 基本条件
    min_age = db.Column(db.Integer, comment='最小年龄')
    max_age = db.Column(db.Integer, comment='最大年龄')
    min_height = db.Column(db.Integer, comment='最小身高')
    max_height = db.Column(db.Integer, comment='最大身高')
    
    # 多选偏好条件（JSON格式存储）
    education_preferences = db.Column(db.Text, comment='学历偏好JSON数组')
    income_preferences = db.Column(db.Text, comment='收入偏好JSON数组')
    occupation_preferences = db.Column(db.Text, comment='职业偏好JSON数组')
    marital_preferences = db.Column(db.Text, comment='婚姻状况偏好JSON数组')
    housing_preferences = db.Column(db.Text, comment='住房偏好JSON数组')
    car_preferences = db.Column(db.Text, comment='购车偏好JSON数组')
    smoking_preferences = db.Column(db.Text, comment='吸烟偏好JSON数组')
    drinking_preferences = db.Column(db.Text, comment='饮酒偏好JSON数组')
    personality_preferences = db.Column(db.Text, comment='性格偏好JSON数组')
    
    # 地区偏好
    city_preferences = db.Column(db.Text, comment='城市偏好JSON数组')
    
    # 其他条件
    has_children_preference = db.Column(db.Integer, default=-1, comment='对方是否有孩子：-1不限0无1有')
    wants_children_preference = db.Column(db.Integer, default=-1, comment='对方是否要孩子：-1不限0不要1要')
    other_requirements = db.Column(db.Text, comment='其他要求')
    
    # 兼容旧字段（保留用于数据迁移）
    education = db.Column(db.String(100), comment='学历要求（旧）')
    income_range = db.Column(db.String(100), comment='收入要求（旧）')
    occupation = db.Column(db.String(200), comment='职业偏好（旧）')
    cities = db.Column(db.String(200), comment='地区偏好（旧）')
    marital_status = db.Column(db.String(50), comment='婚姻状况（旧）')
    has_children = db.Column(db.Integer, comment='是否有孩子（旧）')
    wants_children = db.Column(db.Integer, comment='是否要孩子（旧）')
    housing_requirement = db.Column(db.String(100), comment='住房要求（旧）')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    def to_dict(self):
        """转换为字典"""
        data = {
            'id': self.id,
            'user_id': self.user_id,
            'min_age': self.min_age,
            'max_age': self.max_age,
            'min_height': self.min_height,
            'max_height': self.max_height,
            'has_children_preference': self.has_children_preference,
            'wants_children_preference': self.wants_children_preference,
            'other_requirements': self.other_requirements,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
        
        # 处理JSON字段
        json_fields = [
            'education_preferences', 'income_preferences', 'occupation_preferences',
            'marital_preferences', 'housing_preferences', 'car_preferences',
            'smoking_preferences', 'drinking_preferences', 'personality_preferences',
            'city_preferences'
        ]
        
        for field in json_fields:
            value = getattr(self, field)
            if value:
                try:
                    data[field] = json.loads(value) if isinstance(value, str) else value
                except (json.JSONDecodeError, TypeError):
                    data[field] = []
            else:
                data[field] = []
        
        # 兼容旧字段
        data.update({
            'education': self.education,
            'income_range': self.income_range,
            'occupation': self.occupation,
            'cities': self.cities,
            'marital_status': self.marital_status,
            'has_children': self.has_children,
            'has_children_text': self.get_has_children_text(),
            'wants_children': self.wants_children,
            'wants_children_text': self.get_wants_children_text(),
            'housing_requirement': self.housing_requirement
        })
        
        return data
    
    def get_has_children_text(self):
        """获取是否有孩子文本"""
        children_map = {-1: '不限', 0: '无', 1: '有'}
        return children_map.get(self.has_children_preference, '不限')
    
    def get_wants_children_text(self):
        """获取是否要孩子文本"""
        children_map = {-1: '不限', 0: '不要', 1: '要'}
        return children_map.get(self.wants_children_preference, '不限')
    
    def __repr__(self):
        return f'<MateCriteria {self.user_id}>' 